package com.mercadoutils.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mercadolibre.sdk.Meli;
import com.mercadolibre.sdk.MeliException;
import com.mercadoutils.listeners.SesionListener;
import com.mercadoutils.singletons.PoolConectionsSingleton;
import com.ning.http.client.FluentStringsMap;
import com.ning.http.client.Response;



@Controller
public class ProductListController {
	 protected final Logger logger = Logger.getLogger(getClass());
	    
	    @RequestMapping("/productListPublicados.html")
	    public String handleRequest(Model model) throws MeliException, IOException {
	    	
	        logger.debug("Entrando al listado de productos");
	        HttpSession session = SesionListener.getSession();
	        Meli m = (Meli) session.getAttribute("meli");
	        
	        
	        FluentStringsMap params = new FluentStringsMap();
	        params.add("access_token", m.getAccessToken());
	        Response r = m.get("/users/me",params);
			String resultado = r.getResponseBody().toString(); 
			JsonElement jelement = new JsonParser().parse(resultado); 
		    JsonObject  jobject = jelement.getAsJsonObject();
		    
		    params.clear();
		    params.add("seller_id", jobject.get("id").toString());
		    
		    r = m.get("/sites/MLA/search",params);
		    
		    
		    resultado = r.getResponseBody().toString();
		    jelement = new JsonParser().parse(resultado); 
		    jobject = jelement.getAsJsonObject();
		    System.out.println(jobject.toString());
		    JsonObject jsonPaginas = jobject.getAsJsonObject("paging");
//		    System.out.println(jsonPaginas.toString());
		    JsonArray jsonResults = jobject.getAsJsonArray("results");
//		    System.out.println(jsonResults.toString());
		    
		    String result = "";
		    for(int i=0;i<jsonResults.size();i++){
		    	result+=unMarshallPublicados(jsonResults.get(i).getAsJsonObject());
		    }
		    
		    System.out.println(result);
		    model.addAttribute("rows",result);
			model.addAttribute("nombre",session.getAttribute("nombre"));
			model.addAttribute("apellido",session.getAttribute("apellido"));
			model.addAttribute("role",session.getAttribute("role"));
			model.addAttribute("srcImagen","http://localhost:8080/MercadoUtils/imagenesDB/"+session.getAttribute("srcImagen"));
	        return "productListPublicados";
	    }
	    
	    @RequestMapping("/productListPendientes.html")
	    public String handleRequest2(Model model) throws MeliException, IOException, ServletException, SQLException {
	    	
	        logger.debug("Entrando al listado de productos");
	        HttpSession session = SesionListener.getSession();
	        Meli m = (Meli) session.getAttribute("meli");
	        
	        Connection conexion = PoolConectionsSingleton.getConection();  	
			Statement st = conexion.createStatement();
			ResultSet rs = st.executeQuery("select id,title, subtitle,price, available_quantity,description,item_condition  from item where status = 'eter'");
	        
		    String result = "";
		    while(rs.next()){
		    	result+=unMarshallPendientes(rs);
		    }
		    
		    model.addAttribute("rows",result);	    
			model.addAttribute("nombre",session.getAttribute("nombre"));
			model.addAttribute("apellido",session.getAttribute("apellido"));
			model.addAttribute("role",session.getAttribute("role"));
			model.addAttribute("srcImagen","http://localhost:8080/MercadoUtils/imagenesDB/"+session.getAttribute("srcImagen"));
	        return "productListPendientes";
	    }
	    
	    private String unMarshallPublicados(JsonObject jobject){
	    	String result = "";
	    	System.out.println(jobject.toString());
	    	result+="<tr><td>"+jobject.get("title").toString()+"</td>";
	    	result+="<td>"+jobject.get("price").toString()+"</td>";
	    	result+="<td>"+jobject.get("available_quantity").toString()+"</td>";
	    	result+="<td>"+jobject.get("listing_type_id").toString()+"</td>";
	    	result+="<td>Activo</td>";
	    	result+="<td>"+jobject.get("sold_quantity").toString()+"</td>";
	    	result+="<td>"+jobject.get("condition").toString()+"</td>";
	    	result+="<td>"+jobject.get("stop_time").toString().substring(0, 11)+"\""+"</td>";
	    	result+="<td><a href=http://localhost:8080/MercadoUtils/ItemQuestion.html?id="+jobject.get("id").toString().replaceAll("\"","")+"&title="+jobject.get("title").toString().replaceAll("\"", "").replaceAll(" ", "space")+">Ver Pregutas</a></td>";
	    	result+="<td><a href="+jobject.get("permalink").toString()+">Link</a></td>";
	    	result+="</tr>";
	    	return result;
	    }
	    
	    private String unMarshallPendientes(ResultSet rs) throws SQLException{
	    	String result = "";
	    	result+="<tr><td>"+"<input class=\"uniform\" type=\"checkbox\" value=\""+rs.getString("id")+"\" id=\""+rs.getString("id")+"\">"+"</td>";
	    	result+="<td>"+rs.getString("title")+"</td>";
	    	result+="<td>"+rs.getString("subtitle")+"</td>";
	    	result+="<td>"+rs.getString("price")+"</td>";
	    	result+="<td>"+rs.getString("available_quantity")+"</td>";
	    	result+="<td>"+rs.getString("description")+"</td>";
	    	result+="<td>"+rs.getString("item_condition")+"</td>";
	    	result+="</tr>";
	    	return result;
	    }
}
